import {useEffect,useState} from 'react'
import { clearTimeout } from 'timers';
export const isFalsy = (value: any) => value === 0 ? false: !value
//在一个函数里，改变传入的对象本身是不好的
export const cleanObject = (object: object) =>{
  const result = {...object}
  Object.keys(result).forEach(key => {
    // @ts-ignore
    const value = result[key]
    if(isFalsy(value)) {
      // @ts-ignore
      delete result[key]
    }
  });
  return result
}
export const useMount = (callback:()=>void) =>{
  useEffect(()=>{
    callback()
  },[])
}
// debounce 实现节流
// export const debounce = (func,delay) =>{
//   let timeout;
//   return (...param) => {
//     if(timeout) {
//       window.clearTimeout(timeout);
//     }
//     timeout = setTimeout(function() {
//       func(...param);
//     },delay)
//   }
// }
// const log= debounce(()=>console.log('call'),5000)
// log()
// log()
// log()
export const useDebounce=<V>(value:V,delay?:number)=>{
  console.log(value,delay)
  const [debouncedValue,setDebouncedValue] = useState(value)
  useEffect(()=>{
    //每次在value变化以后，设置一个定时器
    const timeout = setTimeout(()=>setDebouncedValue(value),delay)
    console.log('++++++')
    //每次在上一个useEffect处理完以后再运行
    return () => window.clearTimeout(timeout)
  },[value,delay])
  return debouncedValue
}